using Admin.NET.Application.Entity;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using SqlSugar;

namespace Admin.NET.Application.Service.Report;

/// <summary>
/// 调拨统计报表服务
/// </summary>
[ApiDescriptionSettings("Report", Name = "transfer", Order = 903)]
[Route("api/report/transfer")]
[AllowAnonymous]
public class TransferReportService : IDynamicApiController, ITransient
{
	private readonly ISqlSugarClient _sqlSugarClient;

	public TransferReportService(ISqlSugarClient sqlSugarClient)
	{
		_sqlSugarClient = sqlSugarClient;
	}

	/// <summary>
	/// 调拨统计分页查询（按时间范围、调拨类型、物品类别、仓库等筛选）
	/// </summary>
	[HttpPost("page")]
	public async Task<object> Page([FromBody] GetTransferInput input)
	{
		DateTime? start = input.StartTime?.Date;
		DateTime? end = input.EndTime?.Date;
		if (end != null) end = end.Value.AddDays(1).AddTicks(-1);

		var query = _sqlSugarClient.Queryable<Systransferorder>()
			.WhereIF(start != null, x => x.ApplyDate >= start)
			.WhereIF(end != null, x => x.ApplyDate <= end)
			.WhereIF(!string.IsNullOrWhiteSpace(input.GoodsOrCategory), x => x.GoodsName!.Contains(input.GoodsOrCategory!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.TransferOrderNo), x => x.Code.Contains(input.TransferOrderNo!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.TransferType), x => x.DocumentStatus.ToString().Contains(input.TransferType!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.FromWarehouse), x => x.FromWarehouse!.Contains(input.FromWarehouse!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.ToWarehouse), x => x.ToWarehouse!.Contains(input.ToWarehouse!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.AgentName), x => x.AgentName!.Contains(input.AgentName!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.MakerName), x => x.CreateUserName!.Contains(input.MakerName!))
			.WhereIF(input.OutStatus != null, x => x.OutStatus == input.OutStatus)
			.WhereIF(input.InStatus != null, x => x.InStatus == input.InStatus)
			.LeftJoin<SysOrg>((o, org) => o.OrgId == org.Id)
			.Select((o, org) => new TransferRowOutput
			{
				TransferOrderNo = o.Code,
				ApplyDate = o.ApplyDate,
				FromWarehouse = o.FromWarehouse,
				ToWarehouse = o.ToWarehouse,
				GoodsName = o.GoodsName,
				TransferQuantity = o.TransferQuantity,
				TransferAmount = o.TransferAmount,
				OutStatus = o.OutStatus.ToString(),
				InStatus = o.InStatus.ToString(),
				AgentName = o.AgentName,
				MakerName = o.CreateUserName,
				DeptName = org.Name,
				MakeTime = o.CreateTime,
				Remark = o.Remark
			});

		var total = new RefAsync<int>();
		var list = await query.ToPageListAsync(input.Page, input.PageSize, total);

		return new { result = new { items = list, total = total.Value, page = input.Page, pageSize = input.PageSize } };
	}

	/// <summary>
	/// 调拨统计汇总（调拨单数量、调拨货品数量、调拨产品金额）
	/// </summary>
	[HttpPost("stats")]
	public async Task<object> Stats([FromBody] GetTransferInput input)
	{
		DateTime? start = input.StartTime?.Date;
		DateTime? end = input.EndTime?.Date;
		if (end != null) end = end.Value.AddDays(1).AddTicks(-1);

		var src = _sqlSugarClient.Queryable<Systransferorder>()
			.WhereIF(start != null, x => x.ApplyDate >= start)
			.WhereIF(end != null, x => x.ApplyDate <= end)
			.WhereIF(!string.IsNullOrWhiteSpace(input.GoodsOrCategory), x => x.GoodsName!.Contains(input.GoodsOrCategory!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.TransferOrderNo), x => x.Code.Contains(input.TransferOrderNo!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.TransferType), x => x.DocumentStatus.ToString().Contains(input.TransferType!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.FromWarehouse), x => x.FromWarehouse!.Contains(input.FromWarehouse!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.ToWarehouse), x => x.ToWarehouse!.Contains(input.ToWarehouse!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.AgentName), x => x.AgentName!.Contains(input.AgentName!))
			.WhereIF(!string.IsNullOrWhiteSpace(input.MakerName), x => x.CreateUserName!.Contains(input.MakerName!))
			.WhereIF(input.OutStatus != null, x => x.OutStatus == input.OutStatus)
			.WhereIF(input.InStatus != null, x => x.InStatus == input.InStatus);

		var count = await src.CountAsync();
		var data = await src.Select(x => new { 
			x.TransferQuantity, 
			x.TransferAmount 
		}).ToListAsync();

		int totalQuantity = data.Sum(x => x.TransferQuantity);
		decimal totalAmount = data.Sum(x => x.TransferAmount ?? 0);

		return new { result = new TransferStatsOutput
		{
			TransferOrderCount = count,
			TransferQuantity = totalQuantity,
			TransferAmount = totalAmount
		}};
	}
}

public class GetTransferInput
{
	public DateTime? StartTime { get; set; }
	public DateTime? EndTime { get; set; }
	public string? GoodsOrCategory { get; set; }
	public string? TransferOrderNo { get; set; }
	public string? TransferType { get; set; }
	public string? FromWarehouse { get; set; }
	public string? ToWarehouse { get; set; }
	public string? AgentName { get; set; }
	public string? MakerName { get; set; }
	public DocumentStatusEnum? OutStatus { get; set; }
	public DocumentStatusEnum? InStatus { get; set; }
	public int Page { get; set; } = 1;
	public int PageSize { get; set; } = 10;
}

public class TransferRowOutput
{
	public string TransferOrderNo { get; set; } = string.Empty;
	public DateTime ApplyDate { get; set; }
	public string? FromWarehouse { get; set; }
	public string? ToWarehouse { get; set; }
	public string? GoodsName { get; set; }
	public int TransferQuantity { get; set; }
	public decimal? TransferAmount { get; set; }
	public string? OutStatus { get; set; }
	public string? InStatus { get; set; }
	public string? AgentName { get; set; }
	public string? MakerName { get; set; }
	public string? DeptName { get; set; }
	public DateTime? MakeTime { get; set; }
	public string? Remark { get; set; }
}

public class TransferStatsOutput
{
	public int TransferOrderCount { get; set; }
	public int TransferQuantity { get; set; }
	public decimal TransferAmount { get; set; }
}
